Python common format string method summary [percent sign and format method]

  • 2020-05-12 02:49:21
  • OfStack

This article illustrates the common format string methods of Python. I will share it with you for your reference as follows:

[mode 1] percent sign (%) mode, printf of class C, needs different types.

1. Anonymous tuple. (recommended for low parameters)


>>> ' Name: %s,  Age: %d' % ('walker', 99)
' Name: walker,  Age: 99'

2. Name dict. The key of the dictionary can be reused.


>>> ' Name: %(name)s,  Age: %(age)d,  Length of service: %(age)d' % {'name':'walker', 'age':99}
' Name: walker,  Age: 99,  Length of service: 99'

The format function does not need to specify a string or a numeric type.

1. Anonymous parameters.


>>> ' Name: {0},  Age: {1}'.format('walker', 99)
' Name: walker,  Age: 99'

2, named parameters, parameters can be reused. (recommended for multi-parameter use)


>>> ' Name: {name},  Age: {age},  Length of service: {age}'.format(name='walker', age=99)
' Name: walker,  Age: 99,  Length of service: 99'

More about Python related content interested readers to view this site project: "Python string skills summary", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has helped you with your Python programming.


Related articles: